package com.nw.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by liqun.chen on 2017/5/15.
 * json格式请求
 */
public class HttpUtil {
    private static final String URL = "http://192.168.3.122:8080/mongoJson/query";
    /**
     * json 字符串
     * @return
     */
    public static JSONObject post(String urlStr, JSONObject obj ){
        JSONObject json = null;
        String resp = null;
       /* JSONObject obj = new JSONObject();
        obj.put("token","27689ab6844b44a9b619a02db73118ab");
        obj.put("user_name","syldada");*/
        String query = obj.toString();
        try {
            //URL url = new URL("http://127.0.0.1:8080/mongoJson/query"); //url地址
            URL url = new URL(urlStr); //url地址

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json");
            connection.connect();

            try (OutputStream os = connection.getOutputStream()) {
                os.write(query.getBytes("UTF-8"));
            }

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                String lines;
                StringBuffer sbf = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sbf.append(lines);
                }
                resp = sbf.toString();

            }
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
             json = (JSONObject) JSON.parse(resp);
        }
        return json;
    }
    //测试
    public static void main(String args [] ) {
         JSONObject obj = new JSONObject();
        //obj.put("token","99bd63d7604c4dfa837c8294a6863e2e");
        obj.put("user_name","syldada");
        obj.put("token","99bd63d7604c4dfa837c8294a6863e2e");
        JSONObject jsonObject = post(URL,obj);
        System.out.println(jsonObject);
    }
}